import { useState } from "react";

function DemoA() {
    let [todo, setTodo] = useState("")
    let [list, setList] = useState([])

    let confirm = () => {
        if (!todo.trim()) {
            alert("todo不能为空~")
        };
        setList([...list, { id: Date.now(), task: todo }]);
        setTodo("")
    }

    let addByEnter = e => {
        if (e.keyCode === 13) {
            confirm();
        }
    }

    let delTodo = (id) => {
        setList(list.filter(item => item.id !== id))
    }

    return (
        <div>
            <div>
                <input
                    type="text"
                    value={todo} onChange={e => setTodo(e.target.value)}
                    onKeyUp={e => addByEnter(e)}
                />
                <button onClick={confirm}>添加</button>
            </div>
            <hr />
            <div>
                {
                    list.map((item) =>
                    (
                        <div key={item.id}>
                            <span>{item.id}---
                                <span>{item.task}</span>
                            </span>
                            <button onClick={() => delTodo(item.id)}>X</button>
                        </div>
                    )
                    )
                }
            </div>
        </div>

    )
}

export default DemoA